package com.alipay.rebate.shop.scheduler.orderimport;

import com.alipay.rebate.shop.constants.OrdersConstant;
import com.alipay.rebate.shop.constants.UserIncomeConstant;
import com.alipay.rebate.shop.dao.mapper.OrdersMapper;
import com.alipay.rebate.shop.dao.mapper.RefundOrdersMapper;
import com.alipay.rebate.shop.dao.mapper.UserIncomeMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.helper.UserIncomeBuilder;
import com.alipay.rebate.shop.model.Orders;
import com.alipay.rebate.shop.model.RefundOrders;
import com.alipay.rebate.shop.model.UserIncome;
import com.alipay.rebate.shop.utils.ListUtil;
import com.alipay.rebate.shop.utils.TaobaoUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.math.BigDecimal;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class RefundOrdersImporter {

  private Logger logger = LoggerFactory.getLogger(RefundOrdersImporter.class);

  Gson gson = new GsonBuilder().create();

  @Autowired
  private RefundOrdersMapper refundOrdersMapper;
  @Autowired
  private OrdersMapper ordersMapper;
  @Autowired
  private UserIncomeMapper userIncomeMapper;
  @Autowired
  private UserMapper userMapper;

  private Long REFUND_STATUS_SUCCESS = 2L;

  // 导入渠道维权订单
  @Transactional
  public void importRelationRefundOrders(String startTime){
    logger.debug("-------------start importRelationRefundOrders--------------");
    Long pageNo = 1L;
    // 导入渠道付款订单
    while(true){
      List<RefundOrders> rsp = TaobaoUtil.getRelationRefundOrders(startTime,pageNo);
//      List<RefundOrders> rsp = DingdanxiaUtil.testRefund();
      if(ListUtil.isEmptyList(rsp)){
        break;
      }
      pageNo ++;
      processRefundOrdersList(rsp);
//      break;
    }
  }

  // 导入会员运营维权订单
  @Transactional
  public void importSpeialnRefundOrders(String startTime){

    logger.debug("-------------start importRelationRefundOrders--------------");
    Long pageNo = 1L;
    // 导入渠道付款订单
    while(true){
      List<RefundOrders> rsp = TaobaoUtil.getSpecialRefundOrders(startTime,pageNo);
      if(ListUtil.isEmptyList(rsp)){
        break;
      }
      pageNo ++;
      processRefundOrdersList(rsp);
    }
  }

  public void processRefundOrdersList(List<RefundOrders> rsp){
    logger.debug("refund order list is : {}",gson.toJson(rsp));
    for(RefundOrders refundOrders : rsp){
      processRefundOrders(refundOrders);
    }
  }

  public void processRefundOrders(RefundOrders refundOrders){

    logger.debug("-------------start processRefundOrders--------------");
    // 从数据库获取订单
    Orders orders = ordersMapper.selectByPrimaryKey(refundOrders.getTbTradeId());
    logger.debug("orders is : {}",orders);
    if(orders == null){
      return;
    }
    // 维权订单，修改订单维权状态refundStatus为1
    orders.setRefundStatus(OrdersConstant.REFUND_STATUS);
    ordersMapper.updateByPrimaryKeySelective(orders);

    refundOrders.setUserId(orders.getUserId());
    if (orders.getUserId() == null){
     refundOrders.setUserId(orders.getPromoterId());
    }
    String tradeId = refundOrders.getTbTradeId();
    // 获取维权订单信息
    RefundOrders previousRefundOrders = refundOrdersMapper
        .selectById(tradeId);
    // 保存或者更新维权订单信息
    saveOrUpdateOrderWhenNotComplete(previousRefundOrders,refundOrders);

    if(previousRefundOrders != null &&
        REFUND_STATUS_SUCCESS.equals(previousRefundOrders.getRefundStatus())){
      logger.debug("have handle success refund orders before");
      return;
    }

    // 如果是维权成功状态，那么相应减掉用户收益(集分宝)
    if(REFUND_STATUS_SUCCESS.equals(refundOrders.getRefundStatus())){
      // 查询订单收益列表
      List<UserIncome> userIncomeList = userIncomeMapper
          .selectUserIncomeByOrdersId(orders.getTradeId());
      // 如果用户确实获取了收益
      if(!ListUtil.isEmptyList(userIncomeList)){
        for(UserIncome userIncome: userIncomeList){
          long userId = userIncome.getUserId();
          BigDecimal money = userIncome.getMoney();
          long uit = money.multiply(new BigDecimal("100")).longValue();
          // 如果已经转账给用户，那么进行扣款
          if(UserIncomeConstant.IS_PAID == userIncome.getStatus()){
            if(uit >0){
              userMapper.plusUserUit(-uit,userId);
            }
          }else{// 否则，更改状态(TODO mingweicai)
            // 将收益状态更改为已经付款
            UserIncome nU = new UserIncome();
            nU.setUserIncomeId(userIncome.getUserIncomeId());
            nU.setStatus(UserIncomeConstant.IS_PAID);
            userIncomeMapper.updateByPrimaryKeySelective(nU);
          }
          // 插入用户扣款记录
          Integer type = UserIncomeConstant.REFUND_UN_AWAED_TYPE;
          Integer isPaid = UserIncomeConstant.IS_PAID;
          UserIncome nUserIncome = UserIncomeBuilder
              .buildUitPaidUserIncome(orders, money.negate(),type,userId,isPaid);
          userIncomeMapper.insertSelective(nUserIncome);
        }
      }
    }
    logger.debug("-------------end processRefundOrders--------------");
  }

  private void saveOrUpdateOrderWhenNotComplete(RefundOrders previousRefundOrders,
      RefundOrders refundOrders){
    if(previousRefundOrders == null){
      refundOrdersMapper.insertSelective(refundOrders);
    }else{
      refundOrdersMapper.updateByPrimaryKeySelective(refundOrders);
    }
  }

}
